<template>
	<div id="topicCreate">
		<!-- 专题编辑 -->
		<template>
			<el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="100px"
				class="demo-ruleForm" id="addfrom">
				<el-form-item label="专题标题" prop="mTitle">
					<el-input v-model="ruleForm.mTitle" autocomplete="off"></el-input>
				</el-form-item>
				<el-form-item label="专题子标题" prop="cTitle">
					<el-input v-model="ruleForm.cTitle" autocomplete="off"></el-input>
				</el-form-item>
				<el-form-item label="专题图片" prop="imageUrl">
					<el-upload class="avatar-uploader" :headers="tokens"
						action="http://192.168.1.54:8080/admin/storage/create" :show-file-list="false"
						:on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
						<img v-if="ruleForm.imageUrl" :src="ruleForm.imageUrl" class="avatar">
						<i v-else class="el-icon-plus avatar-uploader-icon"></i>
						<div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过1Mb</div>
					</el-upload>
				</el-form-item>

				<el-form-item label="专题内容" prop="content">
					<myeditor v-model="ruleForm.content" :init="editorInit"></myeditor>
				</el-form-item>
				<el-form-item label="商品低价" prop="lowerPrice">
					<el-input clearable oninput="value=value.replace(/[^\d]/g,'')" v-model="ruleForm.lowerPrice"
						autocomplete="off"></el-input>
				</el-form-item>
				<el-form-item label="阅读量" prop="readNum">
					<el-input v-model="ruleForm.readNum" autocomplete="off"></el-input>
				</el-form-item>
				<el-form-item label="专题商品">
					<!-- 专题商品 -->
					<el-row class="createPro">
						<el-button type="primary" round @click="createProduct">创建商品</el-button>
					</el-row>
					<template>
						<el-table :data="tableData" style="width:700px" :border="true"
							:header-cell-style="{textAlign:'center'}" :cell-style="{textAlign:'center'}">
							<el-table-column prop="id" label="商品ID">
							</el-table-column>
							<el-table-column label="图片">
								<template slot-scope="scope">
									<img :src="scope.row.picUrl" class="goodsImg" />
								</template>
							</el-table-column>
							<el-table-column prop="name" label="商品名称">
							</el-table-column>
							<el-table-column prop="brief" label="商品介绍">
							</el-table-column>
							<el-table-column label="操作">
								<template slot-scope="scope">
									<el-button size="mini" type="danger" @click="handleDelete(scope.$index,scope.row)">
										删除</el-button>
								</template>
							</el-table-column>
						</el-table>
					</template>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
					<el-button @click="cancel">取消</el-button>
				</el-form-item>
			</el-form>
		</template>
		<!-- 创建商品的弹框 -->
		<template>
			<el-dialog title="提示" :visible.sync="dialogVisible" width="60%">
				<el-row id="role-head" >
					<el-input placeholder="请输入商品ID" v-model="goodsId"></el-input>
					<el-input placeholder="请输入商品名称" v-model="name"></el-input>
					<el-button type="primary" icon="el-icon-search" @click="searchGoods">搜索</el-button>
					<el-table :data="tableData2" style="width:700px" :border="true"
						:header-cell-style="{textAlign:'center'}" :cell-style="{textAlign:'center'}" ref="multipleTable"
						@selection-change="changeFun">
						<el-table-column type="selection">
						</el-table-column>
						<el-table-column prop="id" label="商品ID" width="180">
						</el-table-column>
						<el-table-column label="图片">
							<template slot-scope="scope">
								<img :src="scope.row.picUrl" class="goodsImg" />
							</template>
						</el-table-column>
						<el-table-column label="商品名称" prop="name">
						</el-table-column>
					</el-table>
						<!-- 分页操作 -->
						<template>
							<div class="block2" v-if="tableData2.length!=0">
								<el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
									:current-page="page" :page-sizes="[10, 20, 30, 40]" :page-size="limit"
									layout="total, sizes, prev, pager, next, jumper" :total="total">
								</el-pagination>
							</div>
						</template>
				</el-row>
				<span slot="footer" class="dialog-footer">
					<el-button @click="dialogVisible = false">取 消</el-button>
					<el-button type="primary" @click="addProduct">确 定</el-button>
				</span>
			</el-dialog>
		</template>
		
		
		

	</div>
</template>

<script>
	import Editor from "@tinymce/tinymce-vue";
	import {
		addTopic,
		upTopic
	} from '../../https/promotion'
	import {
		allGoods,
		delGoods
	} from '../../https/good'
	export default {
		components: {
			myeditor: Editor
		},
		data() {
			return {
				// 表单的数据
				ruleForm: {
					// 主标题
					mTitle: '',
					// 子标题
					cTitle: '',
					// 专题图片
					imageUrl: '',
					// 专题的内容
					content: '',
					// 商品低价
					lowerPrice: '',
					// 阅读量
					readNum: '',
				},
				rules: {
					mTitle: [{
						required: true,
						trigger: 'blur',
						message: "专题标题不能为空"
					}],
					cTitle: [{
						required: true,
						trigger: 'blur',
						message: '专题子标题不能为空'
					}],
					content: [{
						required: true,
						trigger: 'change',
						message: '内容不能为空'
					}],
					lowerPrice: [{
						required: true,
						trigger: 'blur',
						message: '价格不能为空'
					}]
				},
				// 图片的token值
				tokens: {
					"X-Litemall-Admin-Token": ''
				},
				//表单显示的列表
				tableData: [],
				// 创建商品的弹框
				dialogVisible: false,
				// 商品的列表2
				tableData2: [],
				// 总条数
				total: '',
				// 当前页面
				page: 1,
				// 限制条数
				limit: 10,
				// 商品id
				goodsId: '',
				// 商品编号
				goodsSn: '',
				// 商品的名称
				name: '',
				// 多选框选中的数据
				multipleSelection: [],
				// 商品列表的id
				goods: [],

				// 富文本编辑
				editorInit: {
					language_url: '/tinymce/lang/zh_CN.js',
					language: 'zh_CN',
					height: 400,
					width: 700,
					skin_url: '/tinymce/skins/ui/oxide', // skin路径
					convert_urls: false,
					plugins: [
						'advlist anchor autolink autosave code codesample colorpicker colorpicker contextmenu directionality emoticons fullscreen hr image imagetools importcss insertdatetime link lists media nonbreaking noneditable pagebreak paste preview print save searchreplace spellchecker tabfocus table template textcolor textpattern visualblocks visualchars wordcount'
					],
					toolbar: [
						'searchreplace bold italic underline strikethrough alignleft aligncenter alignright outdent indent  blockquote undo redo removeformat subscript superscript code codesample',
						'hr bullist numlist link image charmap preview anchor pagebreak insertdatetime media table emoticons forecolor backcolor fullscreen'
					],
					images_upload_handler: function(blobInfo, success, failure) {
						const formData = new FormData();
						formData.append('file', blobInfo.blob());
						createStorage(formData)
							.then(res => {
								success(res.data.data.url);
							})
							.catch(() => {
								failure('上传失败，请重新上传');
							});
					}
				},

			}
		},
		methods: {
			handleAvatarSuccess(res, file) {
				// this.imageUrl = URL.createObjectURL(file.raw);
				console.log("success???", this.ruleForm.imageUrl)
				console.log("我是file", file)
				// 这里将图片地址上传
				this.ruleForm.imageUrl = file.response.data.url
			},
			beforeAvatarUpload(file) {
				const isJPG = file.type === 'image/jpeg';
				const isLt1M = file.size / 1024 / 1024 < 1;

				if (!isJPG) {
					this.$message.error('上传头像图片只能是 JPG 格式!');
				}
				if (!isLt1M) {
					this.$message.error('上传头像图片大小不能超过 1MB!');
				}
				return isJPG && isLt1M;
			},
			handleDelete(index, row) {
				console.log("删除", index)
				this.$confirm('此操作将永久删除此数据, 是否继续?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					this.tableData.splice(index, 1)
					this.$notify({
						title: '成功',
						message: '删除成功',
						type: 'success'
					});
					this.goods.splice(index,1)
					console.log("我是删除的goods",this.goods)

				}).catch(() => {
					this.$message({
						type: 'info',
						message: '已取消删除'
					});
				});


			},
			createProduct() {
				// 创建商品的按钮
				this.dialogVisible = true
				// 将数据进行清空
				this.tableData2 = []
				// 绑定的数据进行清零
				this.goodsId=''

			},
			changeFun(val) {
				// 获取多选框的值
				console.log(val)
				this.multipleSelection = val

			},
			addProduct() {
				// 弹框里面的东西进行确定
				this.dialogVisible = false
				// 中间加一层过度，
				this.tableData = this.multipleSelection
				for (let i = 0; i < this.tableData.length; i++) {
					this.goods.push(this.tableData[i].id)
					// console.log("我是goods",this.goods)
				}
				console.log("我是goods",this.goods)
				console.log("我是tabledata",this.tableData)

				
			},
			// 分页功能
			handleSizeChange(val) {
				// 分页改变显示数据
				// console.log(`每页 ${val} 条`);
				this.limit = val
				this.searchGoods()
			},
			handleCurrentChange(val) {
				// 当前页码的数据
				// console.log(`当前页: ${val}`);
				this.page = val
				this.searchGoods()
			},
			
			
			allTopic() {
				// 所有的专题

			},
			searchGoods() {
				// 弹框的搜索商品
				// 这里先调用所有商品的类目
				let params = {
					page: this.page,
					limit: this.limit,
					goodsId: this.goodsId,
					goodsSn: this.goodsSn,
					name: this.name
				}
				allGoods(params).then(res => {
					console.log("所有商品的列表", res)
					this.tableData2 = res.data.data.list
					this.total = res.data.data.total
				}).catch(err => {
					console.log("错误的提交", err)
				})



			},
			cancel(){
				// 取消按钮
				this.$router.push({
					path:'/promotion/topic'
				})
				
			},


			// 提交表单
			submitForm(ruleForm) {
				this.$refs[ruleForm].validate((valid) => {
					if (valid) {
						// alert('submit!');
						let params = {
							// 专题的id
							id:sessionStorage.getItem("id"),
							//专题标题
							title: this.ruleForm.mTitle,
							//专题子标题
							subtitle: this.ruleForm.cTitle,
							//专题图片
							picUrl: this.ruleForm.imageUrl,
							//专题内容
							content: this.ruleForm.content,
							// 商品低价
							price: this.ruleForm.lowerPrice,
							// 阅读量
							readCount: this.ruleForm.readNum,
							// 专题商品
							goods: this.goods,

						}
					upTopic(params).then(res=>{
					
						if(res.data.errmsg=='成功'){
							this.$router.push({
								path:'/promotion/topic'
							})
								console.log("编辑成功",res)
								// 将编辑后的结果进行覆盖
								let test={
									// 主标题
									title:this.ruleForm.mTitle,
									// 子标题
									subtitle:this.ruleForm.cTitle,
									// 专题图片
									picUrl:this.ruleForm.imageUrl,
									// 专题的内容
									content:this.ruleForm.content,
									// 商品低价
									price:this.ruleForm.lowerPrice,
									// 阅读量
									readCount:this.ruleForm.readNum,
									// 专题商品的列表
									goods:this.goods
								}							
								sessionStorage.setItem("editData",JSON.stringify(test))
						}
					}).catch(err=>{
						console.log("失败",err)
					})


					} else {
						console.log('error submit!!');
						return false;
					}
				});

			}



		},
		mounted() {
			// 挂载的时候将值传入进去
			// 将token值进行存储
			this.tokens["X-Litemall-Admin-Token"] = this.Cookies.get('token')
			
			//对传递过来的数据进行接收
			this.id = this.$route.query.id
			if (this.id != undefined) {
				sessionStorage.setItem("id", this.id)
			
			}
			// 刷新页面就在这里进行跳转,效果就是刷新后面的参数不变
			this.$router.push({
				path:'/promotion/topic-edit',
				query: {
					id: sessionStorage.getItem("id")
				}
			})
			
			//这里将数据读取出来
			let editData=JSON.parse(sessionStorage.getItem("editData"))
				// 进行数据的初始化
				// 主标题
				this.ruleForm.mTitle=editData.title,
				// 子标题
				this.ruleForm.cTitle=editData.subtitle,
				// 专题图片
				this.ruleForm.imageUrl=editData.picUrl,
				// 专题的内容
				this.ruleForm.content=editData.content,
				// 商品低价
				this.ruleForm.lowerPrice=editData.price,
				// 阅读量
				this.ruleForm.readNum=editData.readCount
				// 专题商品的列表
				this.goods=editData.goods
				// 这里将商品的列表重新渲染，我们拿到的只是商品id的列表而已
				// 重点是将这个默认的进行重新渲染
				if(this.goods!=undefined){
					for (let i = 0; i<this.goods.length;i++) {
						this.goodsId=this.goods[i]
						let params = {
							page: this.page,
							limit: this.limit,
							goodsId: this.goodsId,
						}
						allGoods(params).then(res => {
							this.tableData.push(res.data.data.list[0])
							// this.tableData=[...res.data.data.list]
							console.log("所有商品的列表", this.tableData)
						}).catch(err => {
							console.log("错误的提交", err)
						})
					}
				}
		
				console.log("商品的列表",this.tableData)
				
			
				
				
				
				
				
				
				
		}

	}
</script>

<style>
	#addfrom .el-input {
		width: 500px;
		min-width: 300px;
	}

	#addfrom .el-form-item__label {
		font-weight: bolder;
	}

	.avatar-uploader .el-upload {
		border: 1px dashed #d9d9d9;
		border-radius: 6px;
		cursor: pointer;
		position: relative;
		overflow: hidden;
	}

	.avatar-uploader .el-upload:hover {
		border-color: #409EFF;
	}

	.avatar-uploader-icon {
		font-size: 28px;
		color: #8c939d;
		width: 120px;
		height: 120px;
		line-height: 120px;
		text-align: center;
	}

	.avatar {
		width: 178px;
		height: 178px;
		display: block;
	}

	.createPro {
		width: 700px;
		display: flex;
		justify-content: flex-end;
	}

	#role-head .el-input {
		width: 150px !important;
		margin-right: 10px;
	}

	.goodsImg {
		width: 40px;
		height: 40px;
	}
	.block2 {
		margin-top: 20px;
	}
</style>
